package cn.lds.healthexamspringboot.service.impl;

import cn.lds.healthexamspringboot.domain.AppointmentRecord;
import cn.lds.healthexamspringboot.dto.ResponseDTO;
import cn.lds.healthexamspringboot.mapper.AppointmentRecordMapper;
import cn.lds.healthexamspringboot.service.AppointmentRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
public class AppointmentRecordServiceImpl implements AppointmentRecordService {

    @Resource
    private AppointmentRecordMapper appointmentRecordMapper;

    @Override
    public ResponseDTO addAppoint(AppointmentRecord appointmentRecord) {

        LocalDateTime appointmentTime = appointmentRecord.getAppointmentTime();
        if (appointmentTime == null) {
            return ResponseDTO.buildError("预约时间不能为空");
        }

        // 检查日期是否为当前日期的后一天
        LocalDate today = LocalDate.now();
        LocalDate requiredDate = today.plusDays(1);
        if (!appointmentTime.toLocalDate().equals(requiredDate)) {
            return ResponseDTO.buildError("预约日期必须为明天");
        }

        // 检查时间是否在08:30到10:30之间
        LocalTime time = appointmentTime.toLocalTime();
        LocalTime start = LocalTime.of(8, 30);
        LocalTime end = LocalTime.of(10, 30);
        if (time.isBefore(start) || time.isAfter(end)) {
            return ResponseDTO.buildError("预约时间必须在08:30到10:30之间");
        }

        appointmentRecordMapper.insert(appointmentRecord);
        return ResponseDTO.buildSuccess();
    }


    /**
     *
     * @param userId   如果需要根据用户id查询，这里是用户id
     * @param pageNum  分页开始页
     * @param pageSize 没页行数
     * @return
     */
    @Override
    public ResponseDTO<PageInfo<AppointmentRecord>> selectAppointByCondition(Integer userId, int pageNum, int pageSize) {

        // 开始分页，pageNum是当前页码，pageSize是每页大小
        PageHelper.startPage(pageNum, pageSize);

        List<AppointmentRecord> appointmentRecords = appointmentRecordMapper.selectAppointMentByCondition(userId);

        PageInfo<AppointmentRecord> appointmentRecordPageInfo = new PageInfo<>(appointmentRecords);


        return ResponseDTO.buildSuccess(appointmentRecordPageInfo);
    }

    @Override
    public ResponseDTO removeAppoint(Integer id) {

        appointmentRecordMapper.removeAppointById(id);

        return ResponseDTO.buildSuccess();
    }
}
